import router from './routers'
import store from '@/store'
import Config from '@/settings'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
import { buildMenus } from '@/api/system/menu'
import { filterAsyncRouter } from '@/store/modules/permission'
import { encrypt } from '@/utils/rsaEncrypt'
import { systemParameterList } from '@/api/systemParameter'

NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/login', '/login_sso', '/unifyauth', '/bindingSuccess']// no redirect whitelist
function handleSystemParameterList() {
  systemParameterList().then(data => {
    const params = {}
    if (data) {
      data.map((item, index) => {
        const parameterValue = item.code
        params[parameterValue] = data[index]
      })
    }
    if (params) {
      localStorage.setItem('messageStore', JSON.stringify(params))
      store.dispatch('page/addPageParmas', params)
    }
    const val = params && params.skin_name && params.skin_name.value ? params.skin_name.value.split(',')[2] : '#409EFF'
    store.dispatch('settings/changeSetting', {
      key: 'theme',
      value: val
    })
  }).catch(() => {
    const val = '#409EFF'
    store.dispatch('settings/changeSetting', {
      key: 'theme',
      value: val
    })
  })
}
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    if (to.path === '/unified_login') {
      document.title = to.meta.title
    } else {
      // todo 使用本地缓存
      const version = localStorage.getItem('version')
      console.log('version', version)
      document.title = to.meta.title + ' - ' + Config.title + `${version ? '  ' + version : ''}`
    }
  }
  NProgress.start()
  // let appType = ''
  if (to.path === '/revitDesignLibrary') {
    if (getToken()) {
      store.dispatch('GetInfo').then(() => { // 拉取user_info
        next()
        NProgress.done()
      })
    } else {
      const user = {
        username: 'revit',
        password: encrypt('123.com'),
        rememberMe: false
      }
      store.dispatch('Login', user).then(() => {
        next()
        NProgress.done()
      })
    }
  } else if (to.path === '/login_sso') {
    if (to.query.redirect !== undefined) {
      // 有重定向
      window.location.href = process.env.VUE_APP_SSO_URL + '&state=' + 1 + ',' + to.query.redirect
    } else {
      // 没有重定向
      window.location.href = process.env.VUE_APP_SSO_URL + '&state=' + 1 + ','
    }
  } else if (to.path === '/sso_callback') {
    const redirect = to.query.state
    const params = {
      code: to.query.code,
      rememberMe: false
    }
    store.dispatch('LoginSso', params).then(() => {
      // 添加页面参数
      handleSystemParameterList()
      if (redirect) {
        // 有重定向
        next({ path: to.query.state })
        NProgress.done()
      } else {
        // 没有重定向
        next({ path: '/' })
        NProgress.done()
      }
    })
  } else if (to.path === '/unifyauth') {
    const params = {
      unifyToken: decodeURIComponent(to.query.uToken)
    }
    store.dispatch('LoginUnified', params).then(() => {
      // 添加页面参数
      handleSystemParameterList()
      if (to.query.t) {
        localStorage.setItem('app-link-type', to.query.t)
      }
      next({ path: to.query.state })
      NProgress.done()
      // 没有重定向
      next({ path: '/' })
      NProgress.done()
    }).catch(() => {
      next({ path: '/' })
      NProgress.done()
    })
  } else {
    if (getToken()) {
      // 已登录且要跳转的页面是登录页
      if (to.path === '/login') {
        next({ path: '/' })
        NProgress.done()
      } else {
        if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
          store.dispatch('GetInfo').then(() => { // 拉取user_info
            if (store.getters.user.username === 'haisum') {
              store.dispatch('LogOut').then(() => {
                if (to.fullPath === '/project/home') {
                  next(`/login?redirect=${'/project/list'}`) // 否则全部重定向到登录页
                } else {
                  next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
                }
              })
            } else {
              // 动态路由，拉取菜单
              loadMenus(next, to)
            }
          }).catch(() => {
            store.dispatch('LogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
          // 登录时未拉取 菜单，在此处拉取
        } else if (store.getters.loadMenus) {
          if (store.getters.user.username === 'haisum') {
            store.dispatch('LogOut').then(() => {
              if (to.fullPath === '/project/home') {
                next(`/login?redirect=${'/project/list'}`) // 否则全部重定向到登录页
              } else {
                next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
              }
            })
          } else {
            // 修改成false，防止死循环
            store.dispatch('updateLoadMenus')
            loadMenus(next, to)
          }
        } else {
          if (store.getters.user.username === 'haisum') {
            store.dispatch('LogOut').then(() => {
              if (to.fullPath === '/project/home') {
                next(`/login?redirect=${'/project/list'}`) // 否则全部重定向到登录页
              } else {
                next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
              }
            })
          } else {
            next()
          }
        }
      }
    } else {
      /* has no token*/
      if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
        next()
      } else {
        if (to.fullPath === '/project/home') {
          next(`/login?redirect=${'/project/list'}`) // 否则全部重定向到登录页
        } else {
          next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
        }
        NProgress.done()
      }
    }
  }
})

export const loadMenus = (next, to) => {
  const params = {
    appType: appType
  }
  buildMenus(params).then(res => {
    const sdata = JSON.parse(JSON.stringify(res))
    const rdata = JSON.parse(JSON.stringify(res))
    const sidebarRoutes = filterAsyncRouter(sdata)
    const rewriteRoutes = filterAsyncRouter(rdata, false, true)
    rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })

    store.dispatch('GenerateRoutes', rewriteRoutes).then(() => { // 存储路由
      router.addRoutes(rewriteRoutes) // 动态添加可访问路由表
      next({ ...to, replace: true })
    })
    store.dispatch('SetSidebarRouters', sidebarRoutes)
  })
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
